package lbframework.classe;

import java.awt.*;
import java.awt.print.*;

public class LBPrintable implements Printable {

    private String aTexto[];

    public LBPrintable(String i_texto) {
        aTexto = i_texto.split("\n", -1);
    }

    @Override
    public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
        //calcula tamanho linha
        Font font = new Font("Serif", Font.PLAIN, 10);
        FontMetrics metrics = g.getFontMetrics(font);
        int lineHeight = metrics.getHeight();

        int linesPerPage = (int) (pf.getImageableHeight() / lineHeight);

        //verifica quantidade paginas
        int totalPage = aTexto.length / linesPerPage;

        if (aTexto.length % linesPerPage != 0) {
            totalPage++;
        }

        if (pageIndex + 1 > totalPage) {
            return NO_SUCH_PAGE;
        }

        //imprime texto
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());

        int start = pageIndex * linesPerPage;
        int end = (pageIndex + 1) * linesPerPage;

        if (end > aTexto.length) {
            end = aTexto.length;
        }

        int y = 0;

        for (int i = start; i < end; i++) {
            if (aTexto[i].isEmpty()) {
                g.drawString(" ", 0, y);
            } else {
                g.drawString(aTexto[i], 0, y);
            }

            y += lineHeight;
        }

        return PAGE_EXISTS;
    }
}
